package co.yixiang.yshop.module.crm.service.crmbills;

import co.yixiang.yshop.framework.security.core.util.SecurityFrameworkUtils;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import co.yixiang.yshop.module.crm.controller.admin.crmbills.vo.*;
import co.yixiang.yshop.module.crm.dal.dataobject.crmbills.CrmBillsDO;
import co.yixiang.yshop.framework.common.pojo.PageResult;
import co.yixiang.yshop.framework.common.pojo.PageParam;
import co.yixiang.yshop.framework.common.util.object.BeanUtils;

import co.yixiang.yshop.module.crm.dal.mysql.crmbills.CrmBillsMapper;

import static co.yixiang.yshop.framework.common.exception.util.ServiceExceptionUtil.exception;
import static co.yixiang.yshop.module.crm.enums.ErrorCodeConstants.*;

/**
 * 账单 Service 实现类
 *
 * @author yshop
 */
@Service
@Validated
public class CrmBillsServiceImpl implements CrmBillsService {

    @Resource
    private CrmBillsMapper billsMapper;

    @Override
    public Long createBills(CrmBillsSaveReqVO createReqVO) {
        // 插入
        CrmBillsDO bills = BeanUtils.toBean(createReqVO, CrmBillsDO.class);
        billsMapper.insert(bills);
        // 返回
        return bills.getId();
    }

    @Override
    public void updateBills(CrmBillsSaveReqVO updateReqVO) {
        // 校验存在
        validateBillsExists(updateReqVO.getId());
        // 更新
        CrmBillsDO updateObj = BeanUtils.toBean(updateReqVO, CrmBillsDO.class);
        billsMapper.updateById(updateObj);
    }

    @Override
    public void deleteBills(Long id) {
        // 校验存在
        validateBillsExists(id);
        // 删除
        billsMapper.deleteById(id);
    }

    private void validateBillsExists(Long id) {
        if (billsMapper.selectById(id) == null) {
            throw exception(BILLS_NOT_EXISTS);
        }
    }

    @Override
    public CrmBillsDO getBills(Long id) {
        return billsMapper.selectById(id);
    }

    @Override
    public PageResult<CrmBillsDO> getBillsPage(CrmBillsPageReqVO pageReqVO) {
        //除了管理员只能查自己的根据ownerUserId 直接看当前用户ID是否为1 用SecurityFrameworkUtils.getLoginUserId()
        if (SecurityFrameworkUtils.getLoginUserId() != 1) {
            pageReqVO.setOwnerUserId(SecurityFrameworkUtils.getLoginUserId());
        }
        return billsMapper.selectPage(pageReqVO);
    }

}
